package net.neptech.service.impl;

import cn.hutool.db.sql.Order;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.neptech.dto.order.DelayMessage;
import net.neptech.dto.order.OrderDTO;
import net.neptech.feign.AppointmentFeign;
import net.neptech.model.emum.OrderStatus;
import net.neptech.model.order.OrderMaster;
import net.neptech.model.vo.OrderVo;
import net.neptech.repository.OrderRepository;
import net.neptech.service.OrderService;
import net.neptech.utils.BeanCopyUtils;
import net.neptech.utils.SimpleOrderNoStr;
import net.neptech.vm.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Component
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private AppointmentFeign appointmentFeign;
    @Resource(name = "delayMessageRedisTemplate")
    private  RedisTemplate<String, DelayMessage> delayMessageRedisTemplate;
    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;
    @Override
    public OrderMaster createOrder(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
//        orderMaster.setOrderNo(orderDTO);
        orderMaster.setUserId(orderDTO.getUserId());
        //订单号
        orderMaster.setOrderNo(SimpleOrderNoStr.next());
        orderMaster.setPatientId(orderDTO.getPatientId());
        //类型
        orderMaster.setOrderType(orderDTO.getTypeId().byteValue());
        //金额
        orderMaster.setAmount(orderDTO.getAmount());
        orderMaster.setId(orderDTO.getId());
        orderMaster.setStatus((byte) 0);

        //截止支付时间
        orderMaster.setPayDeadline(orderDTO.getPayDeadline());
        orderRepository.save(orderMaster);

        return orderMaster;
    }

    @Override
    public ResponseResult<Void> deleteOrder(Long id) {
        try {
            orderRepository.deleteById(id);
        }catch (Exception e){
            log.info("delete:{}",e.getMessage());
            return ResponseResult.fail(5001, "删除失败");
        }
        return ResponseResult.success(200,"删除成功");
    }

    /**
     * 获取订单信息
     * @param orderId
     * @param typeId
     * @return
     */
    @Override
    public OrderVo getOrderById(Long orderId, Byte typeId) {
        OrderMaster orderMaster = orderRepository.findById(orderId).orElse(null);
        return BeanCopyUtils.copyBean(orderMaster, OrderVo.class);
    }
    @Override
    public ResponseResult<Void> updateOrder(Long id, Byte status) {
        try {
            orderRepository.updateStatusById(status,id);
        }catch (Exception e){
            log.info("update:{}",e.getMessage());
            return ResponseResult.fail(5001, "更新失败");
        }
        return ResponseResult.success(200,"更新成功");
    }

    /**
     * 支付订单
     * @param orderDTO
     * @return
     */

    @Override
    @Transactional
    public ResponseResult<Void> payOrder(OrderDTO orderDTO) {
        //判断是否到达支付时间
        Date payDeadline = orderDTO.getPayDeadline();
        if (payDeadline.before(new Date())){
            return ResponseResult.fail(5001, "支付过期");
        }

        //删除定时任务map的订单键
//         delayMessageRedisTemplate.opsForHash().
//                 get("delayed_messages", orderDTO.getId());


        //扣钱
        //修改订单状态
        //修改预约单状态
        Object o = redisTemplate.opsForValue().get("appointment:success:" + orderDTO.getUserId());
        if (o==null){
            return ResponseResult.fail(5001, "订单不存在预约已过期");
        }
        delayMessageRedisTemplate.opsForHash().
                delete( "delayed_messages",orderDTO.getId().toString());
        //远程调用
        ResponseResult<Void> result = appointmentFeign.updateStatusByOrderId(orderDTO.getId(),(byte)1);
        if (result.getCode()==200){
            //消息队列修改订单状态
            kafkaTemplate.send("order_topic","updateOrder",orderDTO.getId());
            redisTemplate.delete("appointment:success:" + orderDTO.getUserId());
                //投放消息队列 添加支付详细
        }
     
        return ResponseResult.success();
    }




}
